import random
from flask import request, jsonify, current_app, make_response, session, g, redirect, render_template
from info.utils.response_code import RET
from . import profile_blu
from info.utils.captcha.captcha import captcha
from info import redis_store, constants, db
import re
from info.models import User,News,Category
from info.libs.yuntongxun import sms
from info.utils.common import login_require
from info.utils.image_storage import storage
'''
个人中心页面：iframe页面嵌套，两个html嵌套。当第一次点击--即为get请求时发送html页面给前端，
当post请求时进行逻辑处理
'''

@profile_blu.route('/info')
@login_require
def user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html', data=data)

'''
基本资料
URL：/user/base_info
nick_name	    昵称
signature		签名
gender	 MAN / WOMEN
'''
@profile_blu.route('/base_info',methods=['GET','POST'])
@login_require
def base_info():
    user = g.user
    if request.method == 'GET':
        data = {
            'user':user.to_dict()
        }
        return render_template('news/user_base_info.html',data=data)
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    if not all([nick_name,signature,gender]):
        return jsonify(erron=RET.PARAMERR,errmsg='参数不完整！')
    if gender not in ['MAN','WOMEN']:
        return jsonify(erron=RET.PARAMERR,errmsg='性别参数错误！')

    # 使用user对象保存用户的基本信息
    user.signature = signature
    user.gender = gender
    user.nick_name = nick_name
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(erron=RET.DBERR,errmsg='提交数据失败！')
    # 更新缓存中昵称数据
    session["nick_name"] = nick_name
    return jsonify(erron=RET.OK,errmsg='OK！')

'''
上传用户头像
1、获取参数
avatar = request.files.get('avatar')
2、校验参数是否存在
3、对图片文件使用read()方法，读取图片内容
4、调用七牛云接口，上传图片到七牛云空间
保存七牛云返回的结果，就是图片的名称
5、保存图片到数据库，保存的是图片的相对路径
七牛云的空间的外链域名+七牛云返回的图片名称
6、拼接图片的绝对路径，返回模板页面的img标签的src属性中
'''
@profile_blu.route('/pic_info',methods=['POST','GET'])
@login_require
def pic_info():
    user = g.user
    data = {
        'user': user.to_dict()
    }
    if request.method == 'GET':
        return render_template('news/user_pic_info.html',data=data)

    avatar = request.files.get('avatar')
    if not avatar:
        return jsonify(erron=RET.PARAMERR,errmsg='参数不存在')
    avatar_data = avatar.read()

    try:
        image_name = storage(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erron=RET.THIRDERR,errmsg='图片上传七牛云失败！')
    # 图片名称保存在用户模型中
    user.avatar_url = image_name
    # 更新后的user保存到数据库中
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(erron=RET.DBERR, errmsg='图片名称保存到数据库失败！')

    # 组合图片的绝对路径发送给前端
    avatar_url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        'avatar_url':avatar_url
    }
    return jsonify(erron=RET.OK, errmsg='OK！',data=data)

"""
用户关注
1、获取参数，页数p，默认1
2、判断参数，整型
3、获取用户信息，定义容器存储查询结果，总页数默认1，当前页默认1
4、查询数据库，查询新闻数据并进行分页，user.followed.paginate
5、获取总页数、当前页、新闻数据
6、定义字典列表，遍历查询结果，添加到列表中
7、返回模板news/user_follow.html, 'total_page',current_page,'users'
"""
@profile_blu.route('/user_follow')
@login_require
def user_follow():
    page = request.args.get('p', '1')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    user = g.user
    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        follows = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据错误')
    user_follow_list = []
    for follow in follows:
        user_follow_list.append(follow.to_dict())
    data = {
        'users': user_follow_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('news/user_follow.html', data=data)

'''
密码修改(其他模块类似)：第一次请求为get请求，将页面发给前端
当是post请求时进行逻辑处理
1、默认get请求加载模板页面
2、获取参数old_password,new_password
3、检查参数的完整性
4、获取用户的信息g.user
5、校验旧密码是否正确
6、保存新密码user.password = new_password
7、提交数据到数据库中
8、返回结果
'''
@profile_blu.route('/pass_info',methods=['POST','GET'])
@login_require
def pass_info():
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    if not all(['old_password','new_password']):
        return jsonify(erron=RET.PARAMERR,errmsg='密码参数不完整！')

    user = g.user
    if  not user.check_password(old_password):
        return jsonify(erron=RET.DATAERR,errmsg='密码错误！')
    user.password= new_password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(erron=RET.DATAERR,errmsg='数据提交失败！')

    return jsonify(erron=RET.OK, errmsg='OK！')

"""
用户收藏
1、获取参数，页数p，默认1
2、判断参数，整型
3、获取用户信息，定义容器存储查询结果，总页数默认1，当前页默认1
4、查询数据库，从用户收藏的的新闻中进行分页，user.collection_news
5、获取总页数、当前页、新闻数据
6、定义字典列表，遍历查询结果，添加到列表中
7、返回模板news/user_collection.html,'total_page',current_page,'collections'
"""

@profile_blu.route('/collection')
@login_require
def collection():
    page = request.args.get('p', '1')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = None
    total_page = 1
    current_page = 1
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())
    data = {
        'collections': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }

    return render_template('news/user_collection.html', data=data)
'''
新闻发布：
title	string	是	新闻标题
category_id	int	是	新闻分类_id
digest	string	是	新闻摘要
index_image	file	是	索引图片
content	string	是	新闻内容
get请求发送页面，查询分类数据并去掉最新
post请求逻辑处理---存
'''
@profile_blu.route('/news_release',methods=['POST','GET'])
@login_require
def news_release():
    user = g.user
    if request.method == 'GET':
        try:
           categories =  Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(erron=RET.DATAERR,errmsg='获取分类数据失败！')
        if not categories:
            return jsonify(erron=RET.NODATA,errmsg='没有分类数据！')
        categoroy_list = []
        for categoroy in categories:
            categoroy_list.append(categoroy.to_dict())
        categoroy_list.pop(0)
        data = {
            'categories':categoroy_list
        }
        return render_template('news/user_news_release.html', data=data)

    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')
    try:
        image_data = index_image.read()
        qiniu_image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.IOERR,errmsg='图片上传七牛云失败！')
    # 构造一个新的新闻对象，存储数据
    news = News()
    news.category_id = category_id
    news.title = title
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + qiniu_image_name
    news.content = content
    news.source = '个人发布'

    # 新闻状态
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    return jsonify(errno=RET.OK, errmsg='OK')


"""
用户新闻列表
1、获取参数，页数p，默认1
2、判断参数，整型
3、获取用户信息，定义容器存储查询结果，总页数默认1，当前页默认1
4、查询数据库，查询新闻数据并进行分页，
5、获取总页数、当前页、新闻数据
6、定义字典列表，遍历查询结果，添加到列表中
7、返回模板news/user_news_list.html 'total_page',current_page,'news_dict_list'
"""
@profile_blu.route('/news_list')
@login_require
def news_list():
    user = g.user
    page = request.args.get('p', '1')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = []
    total_page = 1
    current_page = 1
    try:
        paginate = News.query.filter(News.user_id==user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据错误')
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())
    data = {
        'news_list':news_dict_list,
        'total_page':total_page,
        'current_page':current_page
    }
    return render_template('news/user_news_list.html',data=data)
